package com.bizmda.bizsip.source.rabbitmq.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.*;
import com.bizmda.bizsip.source.api.SourceClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * RabbitMQ接收服务
 */
@Slf4j
@Service
public class SourceQueueListener {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private BizMessageInterface bizMessageInterface = SourceClientFactory.getAppServiceClient(BizMessageInterface.class, "/source1/error");
    private Jackson2JsonMessageConverter jackson2JsonMessageConverter =new Jackson2JsonMessageConverter();

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.bizsip.source1.in", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "exchange.direct.bizsip.source", type = ExchangeTypes.DIRECT, durable = "true", autoDelete = "false"),
            key = "key.bizsip.source1.in"))
    public void onMessage(Message inMessage) {
        try {
            this.process(inMessage);
        } catch (BizException e) {
            log.error("RabbitMQ侦听器出错!",e);
        }
    }

    private void process(Message inMessage) throws BizException {
        Map<String,Object> map = (Map<String,Object>)jackson2JsonMessageConverter.fromMessage(inMessage);
        JSONObject jsonObject = JSONUtil.parseObj(map);
        BizMessage<JSONObject> outBizMessage = null;
        outBizMessage = this.bizMessageInterface.call(jsonObject);
        rabbitTemplate.convertAndSend("exchange.direct.bizsip.source", "key.bizsip.source1.out", outBizMessage.getData(),
                message -> {
                    //设置消息持久化
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                });
        return;
    }
}
